//
//  WKWebviewController.m
//  KaizeOCR
//
//  Created by YYKit on 2017/6/16.
//  Copyright © 2017年 zl. All rights reserved.
//  首页的WKWebview，用于显示公司主页

#import "WXWebviewController.h"
#import <WebKit/WebKit.h>
#import "ShareViewPopTool.h" //分享


#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define Top_Offset HEIGHT==812?88:64

// WKWebView 内存不释放的问题解决
@interface WeakWebViewScriptMessageDelegate : NSObject<WKScriptMessageHandler>

//WKScriptMessageHandler 这个协议类专门用来处理JavaScript调用原生OC的方法
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

@implementation WeakWebViewScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}
#pragma mark - WKScriptMessageHandler
//遵循WKScriptMessageHandler协议，必须实现如下方法，然后把方法向外传递
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}
-(void)dealloc
{
    self.scriptDelegate = nil;
}
@end

@interface WXWebviewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic,strong) WKWebView *wkWebview;
@property (nonatomic,strong) UIProgressView *progress;
@property (nonatomic,strong) UIBarButtonItem *leftBarButton;
@property (nonatomic,strong) UIBarButtonItem *leftBarButtonSecond;
@property (nonatomic,strong)  UIBarButtonItem *negativeSpacer;
@property (nonatomic,strong)  UIBarButtonItem *negativeSpacer2;
@property (nonatomic,assign) BOOL allowZoom;
@property (strong,nonatomic)NSString *currentURL;

@end

@implementation WXWebviewController

#pragma mark --- wk
- (WKWebView *)wkWebview
{
    if (_wkWebview == nil)
    {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
        preference.minimumFontSize = 0;
        //设置是否支持javaScript 默认是支持的
        preference.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preference;
        
        if ([mAPPVersion floatValue]>=9.0) {
            // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
            config.allowsInlineMediaPlayback = YES;
            //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
            config.requiresUserActionForMediaPlayback = YES;
            //设置是否允许画中画技术 在特定设备上有效
            config.allowsPictureInPictureMediaPlayback = YES;
            //设置请求的User-Agent信息中应用程序名称 iOS9后可用
            config.applicationNameForUserAgent = @"com.yjwh.yj";
        }
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WS(weakSelf);
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        if ([mAPPVersion floatValue] <= 10.0) {
            [wkUController addScriptMessageHandler:self  name:@"choosedBank"];
            
            [wkUController addScriptMessageHandler:self  name:@"replyComment"];
            
            [wkUController addScriptMessageHandler:self  name:@"jsToOcWithPrams"];
        }else{
            WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:weakSelf];
            //这个类主要用来做native与JavaScript的交互管理
            [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"choosedBank"];
             [wkUController addScriptMessageHandler:self  name:@"replyComment"];
            [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];
        }
        config.userContentController = wkUController;
        
        //以下代码适配文本大小
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        //用于进行JavaScript注入
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [config.userContentController addUserScript:wkUScript];
        
        
        CGFloat height = getRectNavAndStatusHight;
        
        _wkWebview = [[WKWebView alloc]initWithFrame:CGRectMake(0, height, WIDTH, HEIGHT==812?(HEIGHT - 34-height):HEIGHT-height) configuration:config];
        _wkWebview.UIDelegate = self;
        _wkWebview.navigationDelegate = self;
        _wkWebview.scrollView.delegate = self;
        _wkWebview.backgroundColor = [UIColor clearColor];
        _wkWebview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        _wkWebview.multipleTouchEnabled = YES;
        _wkWebview.autoresizesSubviews = YES;
        _wkWebview.scrollView.alwaysBounceVertical = YES;
        _wkWebview.allowsBackForwardNavigationGestures = YES;/**这一步是，开启侧滑返回上一历史界面**/
        
    }
    return _wkWebview;
}

#pragma mark 加载进度条
- (UIProgressView *)progress
{
    if (_progress == nil)
    {
        _progress = [[UIProgressView alloc]initWithFrame:CGRectMake(0, Top_Offset, WIDTH, 0)];
        _progress.tintColor = mContentHighlightColor;
        _progress.backgroundColor = [UIColor grayColor];
        [self.view addSubview:_progress];
    }
    return _progress;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setBarButtonItem];

}
#pragma mark 添加KVO观察者
- (void)addObserver
{
    //TODO:kvo监听，获得页面title和加载进度值，以及是否可以返回
    [self.wkWebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [self.wkWebview addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    [self.wkWebview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}

#pragma mark 设置BarButtonItem
- (void)setBarButtonItem
{
    //通过imageInset调整item的位置和item之间的位置
    //设置返回按钮
    self.leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:[self addItemWithImage:@"normalBack"
                                                                               imageInset:UIEdgeInsetsMake(0, -10, 0, 10)
                                                                                      size:CGSizeMake(28, 28)
                                                                                    action:@selector(selectedToBack)]];

    //设置关闭按钮
    self.leftBarButtonSecond = [[UIBarButtonItem alloc]initWithCustomView:[self addItemWithImage:@"close"
                                                                                     imageInset:UIEdgeInsetsMake(0, -15, 0, 15)
                                                                                            size:CGSizeMake(28, 28)
                                                                                          action:@selector(selectedToClose)]];

    self.navigationItem.leftBarButtonItems = @[self.leftBarButton];


    if (@available(iOS 11,*)) {
        NSLog(@"** iOS 11 **");
    }else{
        NSLog(@"** Not iOS 11 **");
    }

//    //设置刷新按妞
//    UIBarButtonItem *reloadItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"reload_item"]
//                                                                  style:UIBarButtonItemStylePlain
//                                                                 target:self
//                                                                 action:@selector(selectedToReloadData)];
//    self.navigationItem.rightBarButtonItems = @[reloadItem];

}

#pragma mark 添加item
- (UIButton *)addItemWithImage:(NSString *)imageName imageInset:(UIEdgeInsets)inset size:(CGSize)itemSize action:(SEL)action {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:imageName];
    button.frame = CGRectMake(0, 0, itemSize.width, itemSize.height);
    [button setImageEdgeInsets:inset];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:16];

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = rightItem;

    return button;
}
#pragma mark 关闭并上一界面
- (void)selectedToClose
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 返回上一个网页还是上一个Controller
- (void)selectedToBack
{
    
    if (self.wkWebview.canGoBack == 1 ){
        if ([[self.wkWebview.URL absoluteString] isEqualToString: self.urlString]) {
             [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        [self.wkWebview goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark reload
- (void)selectedToReloadData
{
    [self.wkWebview reload];
}
-(void)shareAction:(UIButton *)sender
{
    [[ShareViewPopTool new]shareDoorType:1 andActivityInfo:@{@"typeInt":@"2"}];//加盟
}
-(void)joinAction:(UIButton *)sender
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"摩嗒嗒提醒您" message:@"是否确定加盟我们" preferredStyle: UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击按钮的响应事件；
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
        [PPNetworkHelper POST:joinUs parameters:parameters success:^(id responseObject) {
            if (YJPPSUCCESS(responseObject)) {
                
            }else{
                
            }
        } failure:^(NSError *error) {
            
        } showLoading:self.view];
    }]];
    //弹出提示框；
    [self presentViewController:alert animated:true completion:nil];
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;//单独适配要优化
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.wkWebview];
    [self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    [self addObserver];
    if (self.wKWebViewType == WKWebView_Type_Join) {
        [self addRightBarButtonItemWithTitle:@"分享" action:@selector(shareAction:)];
        UIButton * joinBtn = [[UIButton alloc]initWithFrame:CGRectMake(mScreenWidth-90, mScreenHeight-120, 75, 75)];
        [joinBtn setTitle:@"加盟" forState:UIControlStateNormal];
        [joinBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        joinBtn.backgroundColor = [UIColor blueColor];
        [joinBtn addTarget:self action:@selector(joinAction:) forControlEvents:UIControlEventTouchUpInside];
        joinBtn.layer.masksToBounds = YES;
        joinBtn.layer.cornerRadius = 37.5;
        [self.view addSubview:joinBtn];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    if(!self.allowZoom){
        return nil;
    }else{
//        return self.wkWebview.scrollView.subviews.firstObject;
        return nil;
    }
}

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    self.allowZoom = YES;
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    
    self.allowZoom = NO;
}

#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //加载进度值
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (object == self.wkWebview)
        {
            [self.progress setAlpha:1.0f];
            [self.progress setProgress:self.wkWebview.estimatedProgress animated:YES];
            if(self.wkWebview.estimatedProgress >= 1.0f)
            {
                [UIView animateWithDuration:1.5f
                                      delay:0.0f
                                    options:UIViewAnimationOptionCurveEaseOut
                                 animations:^{
                                     [self.progress setAlpha:0.0f];
                                 }
                                 completion:^(BOOL finished) {
                                     [self.progress setProgress:0.0f animated:NO];
                                 }];
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    //网页title
    else if ([keyPath isEqualToString:@"title"])
    {
        if (object == self.wkWebview){
            self.title = self.wkWebview.title;
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    //是否可以返回
    else if ([keyPath isEqualToString:@"canGoBack"])
    {
        if (object == self.wkWebview){
            if (self.wkWebview.canGoBack == 1){
                self.navigationItem.leftBarButtonItems = @[self.leftBarButton,self.leftBarButtonSecond];
            }else{
                self.navigationItem.leftBarButtonItems = @[self.leftBarButton];
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    //用message.body获得JS传出的参数体
    NSDictionary * parameter = message.body[@"params"];
    //JS调用OC
    if([parameter[@"code"] isEqualToString:@"choosedBank"]){
        if (self.choosedBankBlock) {
            self.choosedBankBlock(parameter[@"obj"]);
        }
        
        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert];
//        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        }])];
//        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }else if([parameter[@"code"] isEqualToString:@"choosedAddress"]){
        if (self.choosedAddressFinish) {
            self.choosedAddressFinish(parameter[@"obj"]);
        }

    }
    
}

#pragma mark -- WKUIDelegate

/**
 *  web界面中有弹出警告框时调用
 *
 *  @param webView           实现该代理的webview
 *  @param message           警告框中的内容
 *  @param completionHandler 警告框消失调用
 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"HTML的弹出框" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 确认框
//JavaScript调用confirm方法后回调的方法 confirm是js中的确定框，需要在block中把用户选择的情况传递进去
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 在这里处理短暂性的加载错误
/*
 *-1009 没有网络连接
 *-1003
 *-999
 *101
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"ErrorCode:%ld",error.code);
    if (error.code == -1099)
    {
    }
}
#pragma mark 添加返回键和关闭按钮

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark 移除观察者
- (void)dealloc
{
    [[self.wkWebview configuration].userContentController removeScriptMessageHandlerForName:@"choosedBank"];
    [[self.wkWebview configuration].userContentController removeScriptMessageHandlerForName:@"replyComment"];
    [[self.wkWebview configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
    [self.wkWebview removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.wkWebview removeObserver:self forKeyPath:@"canGoBack"];
    [self.wkWebview removeObserver:self forKeyPath:@"title"];
    [self cleanCacheAndCookie];
}
- (void)cleanCacheAndCookie{//清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){[storage deleteCookie:cookie];}//清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    
}
    
  
@end
